package twilight.companion.item;

import net.minecraft.network.chat.Component;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Rarity;
import net.minecraft.world.level.Level;
import twilight.companion.entity.MiniYetiEntity;

public class TwilightContractItem extends Item {
    
    public TwilightContractItem() {
        super(new Item.Properties()
                .stacksTo(1)
                .rarity(Rarity.EPIC)
                .fireResistant()
        );
    }
    
    @Override
    public Component getName(ItemStack stack) {
        if (stack.hasTag() && stack.getTag().contains("contract_type")) {
            String contractType = stack.getTag().getString("contract_type");
            if ("mini_yeti".equals(contractType)) {
                return Component.translatable("item.twilight_companion.mini_yeti_contract");
            }
        }
        return super.getName(stack);
    }
    
    @Override
    public net.minecraft.world.InteractionResultHolder<ItemStack> use(Level level, Player player, InteractionHand hand) {
        ItemStack itemStack = player.getItemInHand(hand);

        if (itemStack.hasTag() && "mini_yeti".equals(itemStack.getTag().getString("contract_type"))) {
            if (!level.isClientSide) {
                MiniYetiEntity miniYeti = new MiniYetiEntity(twilight.companion.init.ModEntities.MINI_YETI.get(), level);
                miniYeti.setPos(player.getX(), player.getY(), player.getZ());
                miniYeti.setTame(true);
                miniYeti.setOwnerUUID(player.getUUID());
                miniYeti.startSummonAnimation();

                if (itemStack.getTag().contains("yeti_data")) {
                    var yetiData = itemStack.getTag().getCompound("yeti_data");
                    
                    if (yetiData.getBoolean("is_giant")) {
                        miniYeti.setGiantWithoutAnimation(true);
                    }

                    if (yetiData.contains("health")) {
                        miniYeti.setHealth(yetiData.getFloat("health"));
                    }

                    if (yetiData.getBoolean("is_crouching")) {
                        miniYeti.setCrouching(true);
                    }
                }
                
                level.addFreshEntity(miniYeti);

                itemStack.removeTagKey("contract_type");
                itemStack.removeTagKey("yeti_data");
                if (itemStack.getTag() != null && itemStack.getTag().isEmpty()) {
                    itemStack.setTag(null);
                }
            }
            return net.minecraft.world.InteractionResultHolder.success(itemStack);
        }
        return net.minecraft.world.InteractionResultHolder.pass(itemStack);
    }
}